package com.wdciti.sccp.iot.position.service;

import com.wdciti.sccp.iot.tsdata.core.api.TSDBQueryWrapper;
import com.wdciti.sccp.iot.tsdata.core.api.TSDBWrapper;
import com.wdciti.sccp.iot.tsdata.impl.iotdb.IotdbQueryWrapper;
import org.apache.iotdb.isession.pool.SessionDataSetWrapper;
import org.apache.iotdb.rpc.IoTDBConnectionException;
import org.apache.iotdb.rpc.StatementExecutionException;
import org.apache.iotdb.session.pool.SessionPool;

import javax.annotation.PreDestroy;

public class ExecuteSQLServiceImpl implements ExecuteSQLService {

    private final TSDBWrapper<SessionPool> tsdbWrapper;

    public ExecuteSQLServiceImpl(TSDBWrapper<SessionPool> tsdbWrapper) {
        this.tsdbWrapper = tsdbWrapper;
    }

    @PreDestroy
    public void preDestroy() {
        if (tsdbWrapper.getSessionWrapper() != null) {
            this.tsdbWrapper.close();
        }
    }

    @Override
    public void executeNonSelectQuery(String sql) {
        try {
            tsdbWrapper.getSessionWrapper().executeNonQueryStatement(sql);
        } catch (StatementExecutionException | IoTDBConnectionException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public TSDBQueryWrapper<SessionDataSetWrapper> executeSelectQuery(String sql, long timeoutInMs) {
        IotdbQueryWrapper wrapper = new IotdbQueryWrapper(tsdbWrapper);
        wrapper.executeQuery(sql, timeoutInMs);
        return wrapper;
    }
}
